package cn.tedu.web.controller;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.druid.sql.visitor.functions.Now;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import org.omg.CosNaming.NamingContextPackage.NotFound;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.tedu.web.entity.Goods;
import cn.tedu.web.mapper.GoodsMapper;
import cn.tedu.web.mapper.ImageMapper;
import cn.tedu.web.service.IGoodsService;
import cn.tedu.web.service.IImageService;
import cn.tedu.web.utils.FileUtil;
import cn.tedu.web.entity.Image;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 商品表 前端控制器
 * </p>
 * goods
 * 
 * @author issen
 * @since 2021-09-24
 */
@SuppressWarnings("all")
@RestController
@RequestMapping("/api/goods")
public class GoodsController {

    @Autowired
    public IGoodsService goodsService;
    @Autowired
    public GoodsMapper goodsMapper;
    @Autowired
    private FileUtil fileUtil;
    @Autowired
    private IImageService imageService;

    @Value("${file.request-path}")
    private String requestPath;

    @ApiOperation(value = "新增")
    @PostMapping("/save")
    public ResponseEntity<Object> save(@RequestBody Goods goods) {
        // goodsService.save(goods);
        goods.setAddTime(LocalDateTime.now());
        goodsService.saveGoods(goods);
        return new ResponseEntity<>("保存成功", HttpStatus.OK);
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("/delete")
    public ResponseEntity<Object> delete(@RequestBody Goods goods) {
        // 删除商品信息之前先删除图片
        Boolean flag = fileUtil.DeleteFolder(goods.getImage());
        if (flag) {
            goodsService.removeById(goods.getId());
            return new ResponseEntity<>("删除成功", HttpStatus.OK);
        } else {
            return new ResponseEntity<>("删除失败", HttpStatus.OK);
        }
    }

    @ApiOperation(value = "条件查询")
    @PostMapping("/filter")
    public ResponseEntity<Object> filter(@RequestBody JSONObject param) {
        QueryWrapper<Goods> qw = new QueryWrapper<>();
        String priceMin = param.getString("priceMin");
        String priceMax = param.getString("priceMax");
        String orderBy = param.getString("orderBy");
        String categoryId = param.getString("categoryId");
        String keyWord = param.getString("keyWord");
        String limit = param.getString("limit");
        if (priceMin != null) {
            qw.between("price", priceMin, priceMax);
        }
        if (categoryId != null) {
            qw.eq("cid", categoryId);
        }
        if (!keyWord.isEmpty()) {
            qw.like("name", keyWord);
        }
        if (!orderBy.isEmpty()) {
            qw.orderByDesc(orderBy);
        }
        qw.eq("status", 1);
        String sql = "limit " + limit;
        qw.last(sql);
        List<Goods> goodsList = goodsService.list(qw);
        return new ResponseEntity<>(goodsList, HttpStatus.OK);
    }

    @ApiOperation(value = "最近商品")
    @GetMapping("/recently")
    public List<Goods> recentlyGoods() {
        return goodsMapper.recentlyGoods();
    }

    @ApiOperation(value = "列表（分页）")
    @GetMapping("/list/{pageNum}/{pageSize}")
    public Object list(@PathVariable("pageNum") String pageNum, @PathVariable("pageSize") String pageSize) {
        IPage<Goods> page = goodsService.listGoods(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        return new ResponseEntity<>(page, HttpStatus.OK);
    }

    @ApiOperation(value = "详情")
    @GetMapping("/get/{id}")
    public ResponseEntity<Object> get(@PathVariable("id") Integer id) {
        Goods goods = new Goods();
        goods.setId(id);

        // 基础信息
        goods = goodsMapper.selectOne(new QueryWrapper<Goods>().eq("status", 1).eq("id", goods.getId()));
        if (goods == null) {
            return new ResponseEntity<>("NotFound", HttpStatus.OK);
        };
        // 补全附加信息
        goods = goodsService.listDetail(goods);
        return new ResponseEntity<>(goods, HttpStatus.OK);
    }

    @ApiOperation(value = "编辑商品详情")
    @PostMapping("/update")
    public ResponseEntity<Object> update(@RequestPart("fileList") MultipartFile[] file,
            @RequestPart("goods") Goods goods, HttpServletRequest request) {
        // 商品上架
        if (goods.getStatus() == 1) {
            goods.setOnTime(LocalDateTime.now());
        }
        List<Image> imageList = new ArrayList<Image>();
        // 在有图片
        if (goods.getImages() != null && goods.getImage().length() > 0) {
            for (Image image : goods.getImages()) {
                if (image.getGid() != null) {
                    imageList.add(image);
                }
            }
        }
        // 有新增
        if (file.length > 0) {
            for (int i = 0; i < file.length; i++) {
                // 获取文件名
                String name = file[i].getOriginalFilename();
                // 生成文件路径
                String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                        + "/" + fileUtil.uploadFile(file[i]);
                imageList.add(new Image(name, filePath));
            }
            goods.setImages(imageList);
            goods.setImage(imageList.get(0).getUrl());
        }
        // 删除了所有图片并且没有新增
        if (goods.getImages() == null && file.length <= 0) {
            goods.setImages(null);
            System.out.println("----------------无图片--------------\n");
        }
        goodsService.updateGoods(goods);
        return new ResponseEntity<>(goodsService.listDetail(goods), HttpStatus.OK);
    }

    @ApiOperation(value = "改变状态")
    @PostMapping("/changeStatus")
    public ResponseEntity<Object> changeStatus(@RequestBody Goods goods, HttpServletRequest request) {
        UpdateWrapper updateWrapper = new UpdateWrapper<>();
        // 商品上架
        if (goods.getStatus() == 1) {
            goods.setOnTime(LocalDateTime.now());
            updateWrapper.set("on_time", goods.getOnTime());
        }
        updateWrapper.set("status", goods.getStatus());
        updateWrapper.eq("id", goods.getId());
        goodsService.update(updateWrapper);
        return new ResponseEntity<>("修改完成", HttpStatus.OK);
    }

    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    public ResponseEntity<Object> upload(@RequestPart("fileList") MultipartFile[] file) {
        // System.out.println(file.length);
        ArrayList<Image> imageList = new ArrayList<Image>();
        if (file.length != 0) {
            for (int i = 0; i < file.length; i++) {
                // 获取文件名
                String name = file[i].getOriginalFilename();
                // 生成文件路径
                String filePath = requestPath + fileUtil.uploadFile(file[i]);
                imageList.add(new Image(name, filePath));
            }
        } else {
            System.out.println("----------------无图片--------------\n");
        }
        // 返回图片列表 包括name和url
        return new ResponseEntity<>(imageList, HttpStatus.OK);
    }

}
